package com.news.admin.interceptor;

import com.news.model.admin.pojos.AdUser;
import com.news.utils.thread.AdminThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始设置AdminThread");
        String userId = request.getHeader("userId");
        log.info("userId:{}",userId);
        if (StringUtils.isNotBlank(userId)){
            AdUser adUser = new AdUser();
            adUser.setId(Integer.valueOf(userId));
            AdminThreadLocalUtil.setUser(adUser);
            log.info("设置完成");
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("postHandle:userId:{}",AdminThreadLocalUtil.getUser().getId());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清理AdminThreadLocalUtil");
        AdminThreadLocalUtil.clear();
    }
}
